package spring.com.rocketmq.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.stereotype.Component;
import spring.com.rocketmq.config.RocketMqProductConfig;

import javax.annotation.Resource;

/*
* rocketmq生产者配置
* */
@Slf4j
@Component //注入容器中
public class RocketMqProduct {

  //引入生产者配置文件信息
   @Resource
   private RocketMqProductConfig config;

   //引入生产者
    private DefaultMQProducer producer;

    public RocketMqProduct(){
        //示例生产者
        //getGroupName:组的名称
        producer = new DefaultMQProducer("CicadaGroup");
        //是否开启vip通道:开通的话，端口会减少2
        producer.setVipChannelEnabled(Boolean.FALSE);
        //绑定地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        //开启通道
        start();
    }

    /*
     * 该对象在调用之前必须调用一次，只能初始化一次
     * */
      private void start(){
        try{
            this.producer.start();
        }catch (MQClientException e){
            e.printStackTrace();
        }

    }

    public DefaultMQProducer getRocketMqProduct(){
        return this.producer;
    }

    /**
     * 一般在应用上下文，使用上下文监听器，进行关闭
     */
    public void shutdown(){
        this.producer.shutdown();
    }
}
